package com.daou.smartpush.service.license;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class AES256 {
    public static SecretKeySpec getKeySpec() throws IOException, NoSuchAlgorithmException {
        byte[] bytes = new byte[32];

        SecretKeySpec spec = null;

        // String keyStr = "12345678901234567890123456789012";
        String keyStr = "12345678901234561234567890123456";
        bytes = Base64.decode(keyStr);

        spec = new SecretKeySpec(bytes, "AES");
        return spec;
    }

    public static String encrypt(String text) throws Exception {
        SecretKeySpec spec = getKeySpec();
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, spec);
        BASE64Encoder enc = new BASE64Encoder();

        return enc.encode(cipher.doFinal(text.getBytes())).toString();
    }

    public static String decrypt(String text) throws Exception {
        SecretKeySpec spec = getKeySpec();
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, spec);
        BASE64Decoder dec = new BASE64Decoder();
        return new String(cipher.doFinal(dec.decodeBuffer(text)));
    }
}
